/*
 * @lc app=leetcode.cn id=102 lang=javascript
 *
 * [102] 二叉树的层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
// 广度优先遍历
// 使用队列，先进先出，处理节点
var levelOrder = function(root) {
  if (!root) return []
  let queue = [root]
  const res = []
  const bfs = () => {
    if (!queue.length) return
    const list = []
    const newQueue = []
    for (let i = 0; i < queue.length; i++) {
      const current = queue[i]
      list.push(current.val)
      if (current.left) {
        newQueue.push(current.left)
      }
      if (current.right) {
        newQueue.push(current.right)
      }
    }
    res.push(list)
    queue = newQueue
    bfs()
  }
  bfs()
  return res
};
// @lc code=end

